package com.jhd.fuzhou.view.special;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;

import com.github.barteksc.pdfviewer.PDFView;
import com.jhd.fuzhou.service.EPrinterService;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.PDFService;
import com.jhd.fuzhou.service.PrinterService;
import com.jhd.fuzhou.util.DocumentPreview;
import com.jhd.fuzhou.util.UploadFile;
import com.jhd.fuzhou.util.UploadSign;
import com.jhd.fuzhou.util.UtilHelper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import static com.jhd.fuzhou.view.login.MainActivity.supervisionInspectionVo;

public class SpecialDocumentInquiryRecordActivity extends BaseActivity {

    private String fileUrl,type,documentNo;
    //private DocumentNoClaimVo documentNoClaimVo=null;
    @BindView(R.id.pdfView)
    PDFView pdfView;
    @BindView(R.id.btn_print)
    Button btn_print;
    private Context context= this;
    private ProgressDialog _dialog;
    private PrinterService printerService;
    private EPrinterService ePrinterService;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_document_preview);
    }

    @Override
    protected void processLogic() {
        application.addDocActivity(this);
        findViewById(R.id.tv_finish).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                application.exitDoc();
            }
        });
        _dialog = new ProgressDialog(context);
        _dialog.setMessage("正在生成现场笔录文书,请稍等...");
        _dialog.show();
        if(UtilHelper.ePrinterType==0){
            printerService = new PrinterService.Builder(this).build();
        }else{
            ePrinterService=new EPrinterService.Builder(this).build();
        }
        fileUrl=getIntent().getStringExtra("fileUrl");
        type=getIntent().getStringExtra("type");
        documentNo=getIntent().getStringExtra("documentNo");
        handler.sendEmptyMessage(1);
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
    }
    @OnClick({R.id.btn_download,R.id.btn_print})
    public void onClick(View v){
        switch (v.getId()){
            case R.id.btn_download:
                UploadFile.copyFile(getExternalFilesDir(null).getPath()+ "/Download/document.pdf",
                        getExternalFilesDir(null).getPath() +"/Download/专项监督/",supervisionInspectionVo.getSupervisedUnitName()+"的现场笔录"+".pdf",context);
                break;
            case R.id.btn_print:
                if(UtilHelper.ePrinterType==0) {
                    printerService.executePrint(btn_print);
                }else {
                    ePrinterService.executePrint(btn_print);
                }
                break;
        }
    }
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {//判断保存本地签名是否成功
                File file1 = new File(getExternalFilesDir(null).getPath() + "/Download/1.png");
                File file2 = new File(getExternalFilesDir(null).getPath() + "/Download/2.png");
                File file3 = new File(getExternalFilesDir(null).getPath() + "/Download/3.png");
                if ((supervisionInspectionVo.getSign1() && !file1.exists()) || (supervisionInspectionVo.getSign2() && !file2.exists()) || (supervisionInspectionVo.getSign3() && !file3.exists())) {
                    handler.sendEmptyMessageDelayed(1, 200);
                } else {
                    if (supervisionInspectionVo.getSign1())
                        UploadSign.uploadSign(application, context, supervisionInspectionVo, 1, "rcjd", file1);
                    if (supervisionInspectionVo.getSign2())
                        UploadSign.uploadSign(application, context, supervisionInspectionVo, 2, "rcjd", file2);
                    if (supervisionInspectionVo.getSign3())
                        UploadSign.uploadSign(application, context, supervisionInspectionVo, 3, "rcjd", file3);
                    handler.sendEmptyMessageDelayed(2, 1000);
                }
            } else if (msg.what == 2) {//上传签名是否成功
                if ((supervisionInspectionVo.getSign1() && supervisionInspectionVo.getUpload1() == null) || (supervisionInspectionVo.getSign2() && supervisionInspectionVo.getUpload2() == null)
                        || (supervisionInspectionVo.getSign3() && supervisionInspectionVo.getUpload3() == null)) {
                    handler.sendEmptyMessageDelayed(2, 200);
                } else {
                    exportInquiryRecordPDF();
                }
            }else if(msg.what==3){//上传文书和显示
                File file=new File(getExternalFilesDir(null).getPath() + "/Download/document.pdf");
                if(_dialog != null)_dialog.cancel();
                UploadFile.showPDF(pdfView,file,context);
                UploadFile.uploadFileAndDocNo(application,context,supervisionInspectionVo,documentNo,file,type,"0","专项监督");
            }
        }
    };

    private void exportInquiryRecordPDF() {
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
//        Retrofit retrofit = UtilHelper.retrofit(application,"http://192.168.1.118:9004/api/");//URL的头
        PDFService vs = retrofit.create(PDFService.class);
        RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json"), DocumentPreview.inquiryRecord(supervisionInspectionVo,application,documentNo,fileUrl, supervisionInspectionVo.getUpload1(), supervisionInspectionVo.getUpload2(), supervisionInspectionVo.getUpload3()));
        Call<ResponseBody> jsonForResultCall = vs.exportInquiryRecordPDF(application.getAccessToken(), requestBody);
        jsonForResultCall.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    if(response.code()==200) {
                        InputStream inputStream=response.body().byteStream();
                        //保存本地
                        writeResponseBodyToDisk(inputStream);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                String msg = "制作文书失败!";
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }

    private void writeResponseBodyToDisk(InputStream inputStream) {
        new Thread(){
            @Override
            public void run() {
                super.run();
                String fileName = "Download/document.pdf";//文件名
                File dir = new File(getExternalFilesDir(null).getPath()+ "/Download/");//路径
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File file = new File(getExternalFilesDir(null).getPath()+"/"+ fileName);
                try{
                    int index;
                    byte[] bytes = new byte[1024];
                    FileOutputStream outputStream = new FileOutputStream(file);
                    while ((index = inputStream.read(bytes)) != -1) {
                        outputStream.write(bytes, 0, index);
                    }
                    outputStream.flush();
                    outputStream.close();
                    inputStream.close();
                    handler.sendEmptyMessage(3);
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }.start();
    }
}